package com.xja.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xja.exception.CustomException;
import com.xja.mapper.ChatMapper;
import com.xja.model.dto.UserMessageDTO;
import com.xja.model.entity.Chat;
import com.xja.model.vo.resp.ChatVO;
import com.xja.service.IChatService;
import com.xja.utils.ChatClientHolder;
import lombok.RequiredArgsConstructor;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.messages.AssistantMessage;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * 对话表 服务实现类
 * </p>
 *
 * @author caijg
 * @since 2025-06-08
 */
@Service
@RequiredArgsConstructor
public class ChatServiceImpl extends ServiceImpl<ChatMapper, Chat> implements IChatService {

    private final ChatClientHolder chatClientHolder;

    @Override
    public ChatVO chat(UserMessageDTO userMessageDTO) {
        // 获取对话模型客户端
        ChatClient simpleChatClient = chatClientHolder.getSimpleChatClient();

        List<Message> messages = Collections.emptyList();
        JSONArray historyMessageArray = JSONUtil.createArray();
        Chat chat = null;

        // 如果对话已存在，获取历史对话记录
        if (userMessageDTO.getSessionId() != null) {
            // 根据sessionId查询对话
            chat = this.lambdaQuery()
                    .eq(Chat::getSessionId, userMessageDTO.getSessionId())
                    .one();

            // 二次确认对话已存在
            if (chat != null && StrUtil.isNotBlank(chat.getRecords())) {
                historyMessageArray = JSONUtil.parseArray(chat.getRecords());
                messages = this.getChatHistory(chat);
            }
        }

        // 调用大模型拿到结果
        String answer = simpleChatClient.prompt(new Prompt(messages))
                .user(userMessageDTO.getContent())
                .call()
                .content();

        historyMessageArray.add(new JSONObject().set("type", "user").set("content", userMessageDTO.getContent()));
        historyMessageArray.add(new JSONObject().set("type", "assistant").set("content", answer));

        // 新对话，创建一个Chat对象
        if (chat == null) {
            chat = new Chat();
            chat.setUserId(userMessageDTO.getUserId());
            chat.setSessionId(UUID.randomUUID().toString());
            chat.setRecords(historyMessageArray.toString());
            chat.setLastQuestion(userMessageDTO.getContent());
            this.save(chat);
        }
        // 老对话，更新
        else {
            chat.setRecords(historyMessageArray.toString());
            chat.setLastQuestion(userMessageDTO.getContent());
            chat.setUpdateTime(LocalDateTime.now());
            this.saveOrUpdate(chat);
        }

        return new ChatVO(answer, chat.getSessionId());
    }

    @Override
    public List<Message> getChatHistory(Chat chat) {
        // 获取历史聊天记录
        String records = chat.getRecords();

        List<Message> messages = new ArrayList<>();

        // 把字符串解析为json数组
        JSONArray jsonArray = JSONUtil.parseArray(records);
        jsonArray.forEach(item -> {
            JSONObject object = (JSONObject) item;
            // 获取消息类型与内容
            String messageType = (String)object.get("type");
            String content = (String) object.get("content");
            if ("user".equals(messageType)) {
                // 用户消息
                messages.add(new UserMessage(content));
            } else if ("assistant".equals(messageType)) {
                // 大模型消息
                messages.add(new AssistantMessage(content));
            }
        });

        return messages;
    }

    @Override
    public List<Chat> history(String userId) {

        return this.lambdaQuery()
                .eq(Chat::getUserId, userId)
                .orderByDesc(Chat::getUpdateTime)
                .list();
    }

    @Override
    public String messages(String sessionId) {
        Chat chat = this.lambdaQuery()
                .eq(Chat::getSessionId, sessionId)
                .one();

        if (chat == null) {
            throw new CustomException("对话记录不存在", 404);
        }

        return chat.getRecords();
    }

    @Override
    public void delete(String sessionId) {
        boolean ok = this.lambdaUpdate()
                .eq(Chat::getSessionId, sessionId)
                .remove();
        if (!ok) {
            throw new CustomException("删除失败", 500);
        }
    }
}